package com.xzx.jedis;

import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisClientConfig;

import java.util.List;

/**
* 
* @author xinzhixuan
* @date 2025/6/6 17:15
* @version 1.0
*/
public class Transaction {
    public static void main(String[] args) {

        JedisClientConfig  config = DefaultJedisClientConfig.builder()
                .user("disrrew")
                .password("rwQeDQhWBMUU1&W%rL#CUgh8*M#MBG")
                .database(4)
                .build();
        try (Jedis jedis = new Jedis("10.0.7.244", 6379, config)) {
            String ping = jedis.ping();
            System.out.println(ping);
            System.out.println(jedis.get("balance"));
            System.out.println(jedis.get("sale"));

            System.out.println("=====");
            // 监控事务中的key，如果发现杯修改，执行事务时会失败
            jedis.watch("balance", "sale");
            // 开启事务
            redis.clients.jedis.Transaction transaction = jedis.multi();
            transaction.decrBy("balance", 10);
            Thread.sleep(10 * 1000);
            transaction.incrBy("sale", 10);
            // 如果事务执行失败，则会返回null，否则就会返回一个List，里面是每个命令的返回值
            List<Object> exec = transaction.exec();
            System.out.println(exec);
            transaction.close();
            System.out.println(jedis.get("balance"));
            System.out.println(jedis.get("sale"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}